<template>
  <div class="app-container">
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="160px"
      :label-position="isPhone ? 'top' : 'left'"
    >
      <el-collapse v-model="activeCollapseItems">
        <!-- 报名年度 -->
        <el-collapse-item title="报名年度" name="yearNum">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报名年度" prop="yearNum">
                <el-input
                  v-model="form.yearNum"
                  placeholder="报名年度"
                  :disabled="true"
                  readonly
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 个人信息 -->
        <el-collapse-item title="个人信息" name="personal">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="userName">
                <el-input
                  v-model="form.userName"
                  placeholder="请输入姓名"
                  maxlength="80"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="头像" prop="avatar">
                <div class="avatar-upload-container">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadImgUrl"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :headers="uploadHeaders"
                    :disabled="isFieldDisabled"
                  >
                    <img v-if="form.avatar" :src="avatarUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"
                      ><Plus
                    /></el-icon>
                  </el-upload>
                  <el-button
                    v-if="form.avatar && !isFieldDisabled"
                    type="danger"
                    size="small"
                    class="avatar-delete-btn"
                    @click="handleDeleteAvatar"
                  >
                    删除头像
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex" :disabled="isFieldDisabled">
                  <el-radio
                    v-for="dict in sys_user_sex"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="民族" prop="nation">
                <el-select
                  v-model="form.nation"
                  placeholder="请选择民族"
                  filterable
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="dict in nation"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="idCard">
                <el-input
                  v-model="form.idCard"
                  placeholder="请输入身份证号"
                  maxlength="18"
                  :disabled="isFieldDisabled"
                  @blur="handleIdCardChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="籍贯" prop="origin">
                <el-input
                  v-model="form.origin"
                  placeholder="请输入籍贯"
                  maxlength="256"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生地" prop="birthPlace">
                <el-input
                  v-model="form.birthPlace"
                  placeholder="请输入出生地"
                  maxlength="256"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="政治面貌" prop="political">
                <el-select
                  v-model="form.political"
                  placeholder="请选择政治面貌"
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="dict in political_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入党时间" prop="joinPartyDate">
                <el-date-picker
                  v-model="form.joinPartyDate"
                  type="date"
                  placeholder="请选择入党时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生年月" prop="birthday">
                <el-date-picker
                  v-model="form.birthday"
                  type="date"
                  placeholder="请选择出生年月"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="true"
                  readonly
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄" prop="age">
                <el-input
                  v-model="form.age"
                  placeholder="年龄"
                  readonly
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input
                  v-model="form.phonenumber"
                  placeholder="请输入手机号码"
                  maxlength="11"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="健康状况" prop="healthStatus">
                <el-select
                  v-model="form.healthStatus"
                  placeholder="请选择健康状况"
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="dict in health_condition"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 家庭主要成员及重要社会关系 -->
        <el-collapse-item
          title="家庭主要成员及重要社会关系"
          name="familyRelation"
        >
          <div style="margin-bottom: 10px">
            <el-button
              v-if="!isFieldDisabled"
              type="primary"
              size="small"
              @click="handleAddItem('family_relation')"
            >
              添加家庭关系
            </el-button>
          </div>
          <el-table
            :data="
              form.items.filter((item) => item.itemType === 'family_relation')
            "
            border
            style="width: 100%"
          >
            <el-table-column
              label="称谓"
              prop="familyRelationTitle"
              width="120"
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.familyRelationTitle"
                  placeholder="请输入称谓"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="姓名" prop="familyRelationName" width="150">
              <template #default="scope">
                <el-input
                  v-model="scope.row.familyRelationName"
                  placeholder="请输入姓名"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="年龄" prop="familyRelationAge" width="120">
              <template #default="scope">
                <el-input
                  v-model="scope.row.familyRelationAge"
                  placeholder="请输入年龄"
                  type="number"
                  :disabled="isFieldDisabled"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="政治面貌"
              prop="familyRelationPolitics"
              width="170"
            >
              <template #default="scope">
                <el-select
                  v-model="scope.row.familyRelationPolitics"
                  placeholder="请选择政治面貌"
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="dict in political_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label="工作单位及职务"
              prop="familyRelationWorkUnit"
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.familyRelationWorkUnit"
                  placeholder="请输入工作单位及职务"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" v-if="!isFieldDisabled">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="handleRemoveItem(scope.$index, 'family_relation')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>

        <!-- 教育信息（全日制） -->
        <el-collapse-item title="教育信息（全日制）" name="fulltime">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最高学历" prop="fulltimeQualification">
                <el-select
                  v-model="form.fulltimeQualification"
                  placeholder="请选择最高学历"
                  style="width: 100%"
                  clearable
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="dict in educational_qualifications"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="毕业高校" prop="fulltimeUniversity">
                <el-input
                  v-model="form.fulltimeUniversity"
                  placeholder="请输入毕业高校"
                  maxlength="255"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="毕业院系" prop="fulltimeCollege">
                <el-input
                  v-model="form.fulltimeCollege"
                  placeholder="请输入毕业院系"
                  maxlength="255"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入学时间" prop="fulltimeJoinDate">
                <el-date-picker
                  v-model="form.fulltimeJoinDate"
                  type="date"
                  placeholder="请选择入学时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="毕业时间" prop="fulltimeGraduateDate">
                <el-date-picker
                  v-model="form.fulltimeGraduateDate"
                  type="date"
                  placeholder="请选择毕业时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="毕业专业" prop="fulltimeMajor">
                <el-input
                  v-model="form.fulltimeMajor"
                  placeholder="请输入毕业专业"
                  maxlength="255"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学位授予单位" prop="fulltimeGrantUnit">
                <el-input
                  v-model="form.fulltimeGrantUnit"
                  placeholder="请输入学位授予单位"
                  maxlength="255"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学科专业名称" prop="fulltimeAcademic">
                <el-select
                  v-model="form.fulltimeAcademic"
                  placeholder="请选择学科专业名称"
                  filterable
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="dict in academic_discipline"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学位授予年月" prop="fulltimeGrantDate">
                <el-date-picker
                  v-model="form.fulltimeGrantDate"
                  type="date"
                  placeholder="请选择学位授予年月"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 教育信息（在职） -->
        <el-collapse-item title="教育信息（在职）" name="onjob">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最高学历" prop="onjobQualification">
                <el-select
                  v-model="form.onjobQualification"
                  placeholder="请选择最高学历"
                  clearable
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="dict in educational_qualifications"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="毕业高校" prop="onjobUniversity">
                <el-input
                  v-model="form.onjobUniversity"
                  placeholder="请输入毕业高校"
                  maxlength="255"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="毕业院系" prop="onjobCollege">
                <el-input
                  v-model="form.onjobCollege"
                  placeholder="请输入毕业院系"
                  maxlength="255"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="毕业时间" prop="onjobGraduateDate">
                <el-date-picker
                  v-model="form.onjobGraduateDate"
                  type="date"
                  placeholder="请选择毕业时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="毕业专业" prop="onjobMajor">
                <el-input
                  v-model="form.onjobMajor"
                  placeholder="请输入毕业专业"
                  maxlength="255"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 外语 -->
        <el-collapse-item title="外语" name="language">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="外语等级" prop="languageLevel">
                <el-select
                  v-model="form.languageLevel"
                  placeholder="请选择外语等级"
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="dict in language_proficiency"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="外语分数" prop="languageScore">
                <el-input
                  v-model="form.languageScore"
                  placeholder="请输入外语分数"
                  maxlength="32"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 工作信息 -->
        <el-collapse-item title="工作信息" name="work">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="现任职单位" prop="trainDeptId">
                <el-select
                  v-model="form.trainDeptId"
                  placeholder="请选择现任职单位"
                  filterable
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="item in deptTreeList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="现任职部门" prop="practiceDeptName">
                <el-input
                  v-model="form.practiceDeptName"
                  placeholder="请输入现任职部门"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="现任职务" prop="position">
                <el-input
                  v-model="form.position"
                  placeholder="请输入现任职务"
                  maxlength="256"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="参加工作时间" prop="firstWorkDate">
                <el-date-picker
                  v-model="form.firstWorkDate"
                  type="date"
                  placeholder="请选择参加工作时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="首次入职中国一汽时间"
                prop="firstJoinFawDate"
              >
                <el-date-picker
                  v-model="form.firstJoinFawDate"
                  type="date"
                  placeholder="请选择首次入职中国一汽时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="performanceN1Label" prop="performanceN1">
                <el-input
                  v-model="form.performanceN1"
                  :placeholder="`请输入${performanceN1Label}`"
                  maxlength="1000"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="performanceN2Label" prop="performanceN2">
                <el-input
                  v-model="form.performanceN2"
                  :placeholder="`请输入${performanceN2Label}`"
                  maxlength="1000"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="performanceN3Label" prop="performanceN3">
                <el-input
                  v-model="form.performanceN3"
                  :placeholder="`请输入${performanceN3Label}`"
                  maxlength="1000"
                  :disabled="isFieldDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职称" prop="professionTitle">
                <el-select
                  v-model="form.professionTitle"
                  placeholder="请选择职称"
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="dict in entry_professional_title"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 工作经历 -->
        <el-collapse-item title="工作经历" name="workExperience">
          <div style="margin-bottom: 10px">
            <el-button
              v-if="!isFieldDisabled"
              type="primary"
              size="small"
              @click="handleAddItem('work_experience')"
            >
              添加工作经历
            </el-button>
          </div>
          <el-table
            :data="
              form.items.filter((item) => item.itemType === 'work_experience')
            "
            border
            style="width: 100%"
          >
            <el-table-column label="开始时间" prop="startTime" width="180">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.startTime"
                  type="date"
                  placeholder="请选择开始时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="结束时间" prop="endTime" width="180">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.endTime"
                  type="date"
                  placeholder="请选择结束时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="工作单位" prop="orgName">
              <template #default="scope">
                <el-input
                  v-model="scope.row.orgName"
                  placeholder="请输入工作单位"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="担任职务" prop="positionName">
              <template #default="scope">
                <el-input
                  v-model="scope.row.positionName"
                  placeholder="请输入担任职务"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark">
              <template #default="scope">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="请输入备注"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" v-if="!isFieldDisabled">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="handleRemoveItem(scope.$index, 'work_experience')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>

        <!-- 获奖情况 -->
        <el-collapse-item title="获奖情况" name="award">
          <div style="margin-bottom: 10px">
            <el-button
              v-if="!isFieldDisabled"
              type="primary"
              size="small"
              @click="handleAddItem('award')"
            >
              添加获奖情况
            </el-button>
          </div>
          <el-table
            :data="form.items.filter((item) => item.itemType === 'award')"
            border
            style="width: 100%"
          >
            <el-table-column label="获得时间" prop="startTime" width="180">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.startTime"
                  type="date"
                  placeholder="请选择获得时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="奖项名称" prop="orgName">
              <template #default="scope">
                <el-input
                  v-model="scope.row.orgName"
                  placeholder="请输入奖项名称"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark">
              <template #default="scope">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="请输入备注"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" v-if="!isFieldDisabled">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="handleRemoveItem(scope.$index, 'award')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>

        <!-- 获得荣誉情况 -->
        <el-collapse-item title="获得荣誉情况" name="honor">
          <div style="margin-bottom: 10px">
            <el-button
              v-if="!isFieldDisabled"
              type="primary"
              size="small"
              @click="handleAddItem('honor')"
            >
              添加荣誉情况
            </el-button>
          </div>
          <el-table
            :data="form.items.filter((item) => item.itemType === 'honor')"
            border
            style="width: 100%"
          >
            <el-table-column label="获得时间" prop="startTime" width="180">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.startTime"
                  type="date"
                  placeholder="请选择获得时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="荣誉名称" prop="orgName">
              <template #default="scope">
                <el-input
                  v-model="scope.row.orgName"
                  placeholder="请输入荣誉名称"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark">
              <template #default="scope">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="请输入备注"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" v-if="!isFieldDisabled">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="handleRemoveItem(scope.$index, 'honor')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>

        <!-- 发明专利情况 -->
        <el-collapse-item title="发明专利情况" name="patent">
          <div style="margin-bottom: 10px">
            <el-button
              v-if="!isFieldDisabled"
              type="primary"
              size="small"
              @click="handleAddItem('patent')"
            >
              添加专利情况
            </el-button>
          </div>
          <el-table
            :data="form.items.filter((item) => item.itemType === 'patent')"
            border
            style="width: 100%"
          >
            <el-table-column label="时间" prop="startTime" width="180">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.startTime"
                  type="date"
                  placeholder="请选择时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="orgName">
              <template #default="scope">
                <el-input
                  v-model="scope.row.orgName"
                  placeholder="请输入专利名称"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark">
              <template #default="scope">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="请输入备注"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" v-if="!isFieldDisabled">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="handleRemoveItem(scope.$index, 'patent')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>

        <!-- 论文 -->
        <el-collapse-item title="论文" name="paper">
          <div style="margin-bottom: 10px">
            <el-button
              v-if="!isFieldDisabled"
              type="primary"
              size="small"
              @click="handleAddItem('paper')"
            >
              添加论文
            </el-button>
          </div>
          <el-table
            :data="form.items.filter((item) => item.itemType === 'paper')"
            border
            style="width: 100%"
          >
            <el-table-column label="时间" prop="startTime" width="180">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.startTime"
                  type="date"
                  placeholder="请选择时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="orgName">
              <template #default="scope">
                <el-input
                  v-model="scope.row.orgName"
                  placeholder="请输入论文名称"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark">
              <template #default="scope">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="请输入备注"
                  :disabled="isFieldDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" v-if="!isFieldDisabled">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="handleRemoveItem(scope.$index, 'paper')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>

        <!-- 工作业绩 -->
        <el-collapse-item title="工作业绩" name="achievement">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="从事工作及主要业绩" prop="achievementDesc">
                <el-input
                  v-model="form.achievementDesc"
                  type="textarea"
                  placeholder="请输入从事工作及主要业绩（脱敏处理，200字以内）"
                  :rows="6"
                  maxlength="600"
                  :disabled="isFieldDisabled"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 报名信息 -->
        <el-collapse-item title="报名信息" name="registration">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="申报专业领域" prop="trainMajor">
                <el-select
                  v-model="form.trainMajor"
                  placeholder="请选择申报专业领域"
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="dict in specialty"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申报高校" prop="trainUniversity">
                <el-select
                  v-model="form.trainUniversity"
                  placeholder="请选择申报高校"
                  filterable
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="dict in university"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培养单位1" prop="trainUnit1Id">
                <el-select
                  v-model="form.trainUnit1Id"
                  placeholder="请选择培养单位1"
                  filterable
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="item in trainingUnitList"
                    :key="item.deptId"
                    :label="item.deptName"
                    :value="item.deptId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培养单位2" prop="trainUnit2Id">
                <el-select
                  v-model="form.trainUnit2Id"
                  placeholder="请选择培养单位2"
                  filterable
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="item in trainingUnitList"
                    :key="item.deptId"
                    :label="item.deptName"
                    :value="item.deptId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培养单位3" prop="trainUnit3Id">
                <el-select
                  v-model="form.trainUnit3Id"
                  placeholder="请选择培养单位3"
                  filterable
                  style="width: 100%"
                  :disabled="isFieldDisabled"
                >
                  <el-option
                    v-for="item in trainingUnitList"
                    :key="item.deptId"
                    :label="item.deptName"
                    :value="item.deptId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 附件上传 -->
        <el-collapse-item title="附件上传" name="agreement">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报名表导出">
                <el-button
                  type="primary"
                  icon="Download"
                  @click="handleExportDetail"
                  :loading="exportDetailLoading"
                  :disabled="exportDetailLoading"
                >
                  报名表导出
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报名表上传" prop="enrollFile">
                <file-upload
                  v-model="form.enrollFile"
                  ref="enrollFileUploadRef"
                  :limit="1"
                  :fileSize="100"
                  :isShowTip="false"
                  :disabled="isFieldDisabled"
                  :fileType="[
                    'pdf',
                    'doc',
                    'docx',
                    'xls',
                    'xlsx',
                    'ppt',
                    'pptx',
                    'zip',
                    '7z',
                    'rar',
                    'jpg',
                    'jpeg',
                    'png',
                  ]"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-table
            :data="enrollTimeFileList"
            border
            style="width: 100%; margin-top: 20px"
          >
            <el-table-column label="名称" prop="name" width="200">
              <template #default="scope">
                {{ scope.row.name || scope.row.fileName || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="模版下载" width="150">
              <template #default="scope">
                <el-button
                  v-if="scope.row.filePath || scope.row.url"
                  link
                  type="primary"
                  icon="Download"
                  @click="handleDownloadTemplate(scope.row)"
                  :disabled="isFieldDisabled"
                >
                  下载
                </el-button>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="文件上传">
              <template #default="scope">
                <file-upload
                  v-model="scope.row.uploadedFile"
                  :limit="1"
                  :fileSize="100"
                  :isShowTip="false"
                  :disabled="isFieldDisabled"
                  :showUploadTip="false"
                  :fileType="[
                    'pdf',
                    'doc',
                    'docx',
                    'xls',
                    'xlsx',
                    'ppt',
                    'pptx',
                    'zip',
                    '7z',
                    'rar',
                    'jpg',
                    'jpeg',
                    'png',
                  ]"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-form>

    <!-- 审批进度组件 -->
    <div v-if="form.approvalInfoId" style="margin-bottom: 20px">
      <approval-progress :approval-info-id="form.approvalInfoId" />
    </div>

    <!-- 审核意见（驳回状态显示） -->
    <el-form-item
      label="审核意见"
      prop="approvalRemark"
      style="margin-bottom: 0"
      v-if="form.approvalStatus === 'rejected'"
    >
      <el-input
        v-model="form.approvalRemark"
        disabled
        type="textarea"
        placeholder="请输入审核意见"
        :rows="3"
        style="width: 100%"
      ></el-input>
    </el-form-item>

    <div class="dialog-footer" style="margin-top: 20px">
      <!-- 详情模式按钮 -->
      <template v-if="isDetailMode">
        <el-button @click="handleCancel">返 回</el-button>
      </template>

      <!-- 审批模式下的审核意见字段和按钮 -->
      <div v-else-if="mode === 'approve'" style="margin-bottom: 20px">
        <el-form-item
          label="审核意见"
          prop="approvalRemark"
          style="margin-bottom: 0"
        >
          <el-input
            v-model="form.approvalRemark"
            type="textarea"
            placeholder="请输入审核意见"
            :rows="3"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        <el-button
          type="success"
          @click="handleApprovePass"
          :loading="approvePassLoading"
          :disabled="approvePassLoading"
          style="margin-top: 10px; margin-right: 10px"
        >
          通 过
        </el-button>
        <el-button
          type="danger"
          @click="handleApproveReject"
          :loading="approveRejectLoading"
          :disabled="approveRejectLoading"
          style="margin-top: 10px; margin-right: 10px"
        >
          驳 回
        </el-button>
        <el-button @click="handleCancel" style="margin-top: 10px"
          >取 消</el-button
        >
      </div>

      <!-- 普通编辑模式按钮 -->
      <template v-else>
        <el-button
          type="primary"
          @click="submitForm"
          :loading="submitLoading"
          :disabled="submitLoading"
          style="margin-right: 10px"
        >
          信息保存
        </el-button>
        <el-button
          v-if="
            !form.approvalStatus ||
            form.approvalStatus === 'no_submit' ||
            form.approvalStatus === 'rejected'
          "
          type="primary"
          @click="saveAndSubmit"
          :loading="saveSubmitLoading"
          :disabled="saveSubmitLoading"
          style="margin-right: 10px"
        >
          信息提交
        </el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </template>
    </div>
  </div>
</template>

<script setup name="SignListEdit">
import { getCurrentInstance, ref, reactive, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getDetail, addItem, editItem } from "@/api/sign-list";
import {
  getList as getSignTimeList,
  getValidEnrollTime,
} from "@/api/sign-time";
import {
  getTrainFieldDropdown,
  getUniversityDropdown,
  getTrainDeptDropdown,
  getDeptTree,
} from "@/api/common";
import { getRegisterList } from "@/api/login";
import { submitApproval, handleApproval } from "@/api/approval";
import { useDict } from "@/utils/dict";
import { isPhone } from "@/utils/index";
import FileUpload from "@/components/FileUpload/index.vue";
import ApprovalProgress from "@/components/ApprovalProgress";
import useUserStore from "@/store/modules/user";
import { getToken } from "@/utils/auth";
import { Plus } from "@element-plus/icons-vue";
import { downloadFileByApi, downloadFile } from "@/utils/fileDownload";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const id = route.params.id === "add" ? undefined : route.params.id;
const mode = route.query.mode || (id ? "edit" : "add");
const isDetailMode = computed(() => mode === "detail" || mode === "view");
// 字段是否禁用：详情模式或审批模式下都禁用
const isFieldDisabled = computed(
  () => mode === "detail" || mode === "view" || mode === "approve"
);

const formRef = ref();
const fileUploadRef = ref();
const enrollFileUploadRef = ref();
const submitLoading = ref(false);
const saveSubmitLoading = ref(false);
const approvePassLoading = ref(false);
const approveRejectLoading = ref(false);
const exportDetailLoading = ref(false);
const yearOptions = ref([]);
const trainingUnitList = ref([]);
const deptTreeList = ref([]);
const registerList = ref([]);
const enrollTimeFileList = ref([]);

// 头像上传相关
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/common/upload");
const uploadHeaders = ref({ Authorization: "Bearer " + getToken() });

// 头像 URL 计算属性
const avatarUrl = computed(() => {
  if (!form.avatar) return "";
  const avatar = String(form.avatar);
  if (
    avatar.startsWith("http://") ||
    avatar.startsWith("https://") ||
    avatar.startsWith("//")
  ) {
    return avatar;
  }
  if (!avatar.includes(baseUrl)) {
    return baseUrl + (avatar.startsWith("/") ? avatar : "/" + avatar);
  }
  return avatar;
});

// 获取用户信息
const userStore = useUserStore();
// 判断是否为学生角色
const isStudentRole = computed(() => {
  const roles = userStore.roles || [];
  return roles.length > 0 && roles[0] === "student";
});

// 绩效年度标签计算属性
const performanceN1Label = computed(() => {
  if (!form.yearNum) return "N-1年绩效";
  const year = Number(form.yearNum) - 2;
  return `${year}年绩效`;
});

const performanceN2Label = computed(() => {
  if (!form.yearNum) return "N-2年绩效";
  const year = Number(form.yearNum) - 3;
  return `${year}年绩效`;
});

const performanceN3Label = computed(() => {
  if (!form.yearNum) return "N-3年绩效";
  const year = Number(form.yearNum) - 4;
  return `${year}年绩效`;
});
const activeCollapseItems = ref([
  "yearNum",
  "personal",
  "familyRelation",
  "fulltime",
  "onjob",
  "language",
  "work",
  "workExperience",
  "award",
  "honor",
  "patent",
  "paper",
  "achievement",
  "registration",
  "agreement",
]);

// 字典数据
const {
  sys_user_sex,
  nation,
  political_status,
  health_condition,
  educational_qualifications,
  language_proficiency,
  entry_professional_title,
  academic_discipline,
} = useDict(
  "sys_user_sex",
  "nation",
  "political_status",
  "health_condition",
  "educational_qualifications",
  "language_proficiency",
  "entry_professional_title",
  "academic_discipline"
);

const specialty = ref([]);
const university = ref([]);

const form = reactive({
  id: undefined,
  yearNum: undefined,
  // 个人信息
  userName: undefined,
  userId: undefined,
  avatar: undefined,
  sex: "0",
  nation: undefined,
  idCard: undefined,
  origin: undefined,
  birthPlace: undefined,
  political: undefined,
  joinPartyDate: undefined,
  birthday: undefined,
  age: undefined,
  phonenumber: undefined,
  healthStatus: undefined,
  // 教育信息（全日制）
  fulltimeQualification: undefined,
  fulltimeUniversity: undefined,
  fulltimeCollege: undefined,
  fulltimeJoinDate: undefined,
  fulltimeGraduate_date: undefined,
  fulltimeMajor: undefined,
  fulltimeGrantUnit: undefined,
  fulltimeAcademic: undefined,
  fulltimeGrantDate: undefined,
  // 教育信息（在职）
  onjobQualification: undefined,
  onjobUniversity: undefined,
  onjobCollege: undefined,
  fulltimeGraduateDate: undefined,
  onjobMajor: undefined,
  // 外语
  languageLevel: undefined,
  languageScore: undefined,
  // 工作信息
  trainDeptId: undefined,
  practiceDeptName: undefined,
  position: undefined,
  firstWorkDate: undefined,
  firstJoinFawDate: undefined,
  performanceN1: undefined,
  performanceN2: undefined,
  performanceN3: undefined,
  professionTitle: undefined,
  // 工作业绩
  achievementDesc: undefined,
  // 报名信息
  trainMajor: undefined,
  trainUniversity: undefined,
  trainUnit1Id: undefined,
  trainUnit2Id: undefined,
  trainUnit3Id: undefined,
  // 附件
  fileObjects: [],
  enrollFile: [],
  // 明细项
  items: [],
  // 审批信息
  approvalInfoId: undefined,
  approvalNodeId: undefined,
  approvalStatus: undefined,
  approvalRemark: undefined,
});

const rules = {
  // yearNum: [{ required: true, message: "请选择报名年度", trigger: "change" }],
  // userName: [{ required: true, message: "请选择或输入姓名", trigger: "change" }],
  // trainMajor: [{ required: true, message: "请选择申报专业领域", trigger: "change" }],
  // trainUniversity: [{ required: true, message: "请选择申报高校", trigger: "change" }],
};

// 获取注册列表
const fetchRegisterList = async () => {
  if (isStudentRole.value) {
    // 学生角色不需要加载注册列表
    return;
  }
  try {
    const res = await getRegisterList({
      pageNum: 1,
      pageSize: 1000,
    });
    registerList.value = res.rows || [];
    // 如果已加载详情且有姓名，尝试回显性别和民族
    if (id && form.userName) {
      handleUserNameChange(form.userName);
    }
  } catch (error) {
    console.error("获取注册列表失败:", error);
  }
};

// 选择姓名后自动填充性别和民族
const handleUserNameChange = (userName) => {
  if (!userName) {
    return;
  }
  const selectedUser = registerList.value.find(
    (item) => item.userName === userName
  );
  if (selectedUser) {
    // 保存用户ID
    if (selectedUser.userId !== undefined && selectedUser.userId !== null) {
      form.userId = selectedUser.userId;
    }
    // 回显性别
    if (selectedUser.sex !== undefined && selectedUser.sex !== null) {
      form.sex = selectedUser.sex;
    }
    // 回显民族
    if (selectedUser.nation !== undefined && selectedUser.nation !== null) {
      form.nation = selectedUser.nation;
    }
  }
};

// 根据身份证号计算出生日期和年龄
const handleIdCardChange = () => {
  if (form.idCard && form.idCard.length === 18) {
    const birthStr = form.idCard.substring(6, 14);
    const year = birthStr.substring(0, 4);
    const month = birthStr.substring(4, 6);
    const day = birthStr.substring(6, 8);
    form.birthday = `${year}-${month}-${day}`;

    // 计算年龄
    const birthDate = new Date(
      parseInt(year),
      parseInt(month) - 1,
      parseInt(day)
    );
    const today = new Date();
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    if (
      monthDiff < 0 ||
      (monthDiff === 0 && today.getDate() < birthDate.getDate())
    ) {
      age--;
    }
    form.age = age;
  } else if (form.idCard && form.idCard.length === 15) {
    // 处理15位身份证号
    const birthStr = form.idCard.substring(6, 12);
    const year = "19" + birthStr.substring(0, 2);
    const month = birthStr.substring(2, 4);
    const day = birthStr.substring(4, 6);
    form.birthday = `${year}-${month}-${day}`;

    // 计算年龄
    const birthDate = new Date(
      parseInt(year),
      parseInt(month) - 1,
      parseInt(day)
    );
    const today = new Date();
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    if (
      monthDiff < 0 ||
      (monthDiff === 0 && today.getDate() < birthDate.getDate())
    ) {
      age--;
    }
    form.age = age;
  } else {
    // 身份证号格式不正确，清空出生年月和年龄
    form.birthday = undefined;
    form.age = undefined;
  }
};

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG =
    file.type === "image/jpeg" ||
    file.type === "image/png" ||
    file.type === "image/jpg";
  const isLt2M = file.size / 1024 / 1024 < 50;

  if (!isJPG) {
    proxy.$modal.msgError("上传头像图片只能是 JPG/PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    proxy.$modal.msgError("上传头像图片大小不能超过 50MB!");
    return false;
  }
  return true;
};

// 头像上传成功回调
const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    form.avatar = response.fileName;
    proxy.$modal.msgSuccess("头像上传成功");
  } else {
    proxy.$modal.msgError(response.msg || "头像上传失败");
  }
};

// 删除头像
const handleDeleteAvatar = () => {
  proxy.$modal
    .confirm("确认删除头像吗？")
    .then(() => {
      form.avatar = undefined;
      proxy.$modal.msgSuccess("头像已删除");
    })
    .catch(() => {});
};

// 添加明细项
const handleAddItem = (itemType) => {
  if (itemType === "family_relation") {
    form.items.push({
      itemType,
      familyRelationTitle: undefined,
      familyRelationName: undefined,
      familyRelationAge: undefined,
      familyRelationPolitics: undefined,
      familyRelationWorkUnit: undefined,
    });
  } else {
    form.items.push({
      itemType,
      startTime: undefined,
      endTime: undefined,
      orgName: undefined,
      positionName: undefined,
      remark: undefined,
    });
  }
};

// 删除明细项
const handleRemoveItem = (index, itemType) => {
  const filteredItems = form.items.filter((item) => item.itemType === itemType);
  const item = filteredItems[index];
  if (item) {
    const globalIndex = form.items.findIndex((i) => i === item);
    if (globalIndex !== -1) {
      form.items.splice(globalIndex, 1);
    }
  }
};

// 获取年份选项并自动设置报名年度
const fetchYearOptions = async () => {
  try {
    const res = await getSignTimeList({
      pageNum: 1,
      pageSize: 1000,
    });
    yearOptions.value = (res.rows || []).map((item) => ({
      label: item.yearNum,
      value: item.yearNum,
    }));

    // 如果是新增模式，自动获取当前激活任务的年度
    if (!id) {
      // 查找状态为 enable 的激活任务
      const activeTask = (res.rows || []).find(
        (item) => item.status === "enable"
      );
      if (activeTask && activeTask.yearNum) {
        form.yearNum = activeTask.yearNum;
      }
    }
  } catch (error) {
    console.error("获取入学年份下拉数据失败:", error);
  }
};

// 获取下拉选项
const fetchDropdownOptions = async () => {
  try {
    const params = {};
    const [specialtyRes, universityRes, trainDeptRes, deptTreeRes] = await Promise.all([
      getTrainFieldDropdown(params),
      getUniversityDropdown(params),
      getTrainDeptDropdown(params),
      getDeptTree(params)
    ]);

    specialty.value = specialtyRes.data || [];
    university.value = universityRes.data || [];
    trainingUnitList.value = trainDeptRes.data || [];
    deptTreeList.value = (deptTreeRes.data || []).filter(t => !t.disabled);
  } catch (error) {
    console.error("获取下拉选项失败:", error);
    proxy.$modal.msgError("获取下拉选项失败");
  }
};

// 加载详情
const loadDetail = async () => {
  let rId = id || '0';

  try {
    const res = await getDetail(rId);
    if (res.data) {
      Object.assign(form, res.data);
      // 确保 items 和 fileObjects 是数组
      if (!Array.isArray(form.items)) {
        form.items = [];
      }
      if (!Array.isArray(form.fileObjects)) {
        form.fileObjects = [];
      }
      if (form.enrollFile) {
        form.enrollFile = [{
          url: form.enrollFile,
          name: form.enrollFile.split("/").pop(),
        }];
      }
      // 处理文件数据格式，转换为 file-upload 组件需要的格式
      if (Array.isArray(form.fileObjects) && form.fileObjects.length > 0) {
        form.fileObjects = form.fileObjects
          .filter((t) => t.fileType !== "template_upload")
          .map((file) => {
            if (typeof file === "string") {
              return { name: file, url: file };
            }
            return {
              name: file.fileName || file.filePath || "",
              url: file.filePath || file.url || "",
            };
          });
      }
      const aList = res.data.fileObjects.filter(
        (t) => t.fileType === "template_upload"
      );
      enrollTimeFileList.value = form.validTime.fileObjects.map((file) => ({
        ...file,
        name: file.fileName || file.name || "",
        uploadedFile: aList.find((t) => t.fileName === file.fileName)
          ? [aList.find((t) => t.fileName === file.fileName)?.filePath]
          : [],
      }));

      console.log(enrollTimeFileList.value, "xxxx");
      // 如果有身份证号，自动计算出生年月和年龄
      if (form.idCard) {
        handleIdCardChange();
      }
      // 审批模式下清空审核意见
      if (mode === "approve") {
        form.approvalRemark = "";
      }
    }
  } catch (error) {
    console.error("获取详情失败:", error);
    proxy.$modal.msgError("获取详情失败");
  }
};

// 提交表单
const submitForm = () => {
  if (submitLoading.value) return Promise.resolve();

  return new Promise((resolve, reject) => {
    proxy.$refs["formRef"].validate((valid) => {
      if (valid) {
        submitLoading.value = true;

        // 整理文件数据
        let fileObjects = [];
        if (fileUploadRef.value && fileUploadRef.value.fileList) {
          fileObjects = fileUploadRef.value.fileList.map((t) => ({
            fileType: "attachment",
            filePath: t.url || t.name,
            fileName: t.name ? t.name.split("/").pop() || t.name : "",
          }));
        } else if (
          Array.isArray(form.fileObjects) &&
          form.fileObjects.length > 0
        ) {
          // 如果已有文件数据，直接使用
          fileObjects = form.fileObjects.map((file) => {
            if (typeof file === "string") {
              return {
                fileType: "attachment",
                filePath: file,
                fileName: file.split("/").pop() || file,
              };
            }
            return {
              fileType: file.fileType || "attachment",
              filePath: file.filePath || file.url || file,
              fileName:
                file.fileName ||
                (typeof file === "string" ? file.split("/").pop() : ""),
            };
          });
        }

        // 整理表格中上传的文件
        const tableUploadedFiles = [];
        enrollTimeFileList.value.forEach((item) => {
          if (
            item.uploadedFile &&
            !(
              Array.isArray(item.uploadedFile) && item.uploadedFile.length === 0
            )
          ) {
            const files = Array.isArray(item.uploadedFile)
              ? item.uploadedFile
              : [item.uploadedFile];
            files.forEach((file) => {
              tableUploadedFiles.push({
                fileType: "template_upload",
                templateId: item.id || item.fileId,
                templateName: item.name || item.fileName,
                filePath:
                  typeof file === "string"
                    ? file
                    : file.url || file.filePath || file.name,
                fileName: item.name || item.fileName,
              });
            });
          }
        });

        // 合并所有文件
        const allFileObjects = [...fileObjects, ...tableUploadedFiles];

        // 整理明细项数据
        const items = form.items.map((item) => {
          if (item.itemType === "family_relation") {
            return {
              itemType: item.itemType,
              familyRelationTitle: item.familyRelationTitle,
              familyRelationName: item.familyRelationName,
              familyRelationAge: item.familyRelationAge,
              familyRelationPolitics: item.familyRelationPolitics,
              familyRelationWorkUnit: item.familyRelationWorkUnit,
            };
          } else {
            return {
              itemType: item.itemType,
              startTime: item.startTime,
              endTime: item.endTime,
              orgName: item.orgName,
              positionName: item.positionName,
              remark: item.remark,
            };
          }
        });

        const submitData = {
          ...form,
          fileObjects: allFileObjects,
          items,
        };

        delete submitData.validTime;
        if (Array.isArray(submitData.enrollFile)) {
          submitData.enrollFile = submitData.enrollFile[0]?.url || "";
        }

        if (form.id != undefined) {
          editItem(submitData)
            .then(() => {
              proxy.$modal.msgSuccess("修改成功");
              // router.back();
              resolve();
            })
            .catch((error) => {
              console.error("修改失败:", error);
              submitLoading.value = false;
              reject(error);
            }).finally(() => {
              submitLoading.value = false;
            });
        } else {
          addItem(submitData)
            .then((res) => {
              form.id = res.data;
              console.log(form.id, "xxxx", res);
              proxy.$modal.msgSuccess("新增成功");
              resolve(res.data);
            })
            .catch((error) => {
              console.error("新增失败:", error);
              submitLoading.value = false;
              reject(error);
            }).finally(() => {
              submitLoading.value = false;
            });
        }
      }
    });
  });
};

// 保存并提交
const saveAndSubmit = () => {
  if (saveSubmitLoading.value) return;

  // 校验必填字段（包含协议列表）
  const errors = validateSubmitFields();
  if (errors.length > 0) {
    ElMessage.warning(errors[0]);
    return;
  }

  saveSubmitLoading.value = true;

  // 整理文件数据
  let fileObjects = [];
  if (fileUploadRef.value && fileUploadRef.value.fileList) {
    fileObjects = fileUploadRef.value.fileList.map((t) => ({
      fileType: "attachment",
      filePath: t.url || t.name,
      fileName: t.name ? t.name.split("/").pop() || t.name : "",
    }));
  } else if (Array.isArray(form.fileObjects) && form.fileObjects.length > 0) {
    fileObjects = form.fileObjects.map((file) => {
      if (typeof file === "string") {
        return {
          fileType: "attachment",
          filePath: file,
          fileName: file.split("/").pop() || file,
        };
      }
      return {
        fileType: file.fileType || "attachment",
        filePath: file.filePath || file.url || file,
        fileName:
          file.fileName ||
          (typeof file === "string" ? file.split("/").pop() : ""),
      };
    });
  }

  // 整理表格中上传的文件
  const tableUploadedFiles = [];
  enrollTimeFileList.value.forEach((item) => {
    if (
      item.uploadedFile &&
      !(Array.isArray(item.uploadedFile) && item.uploadedFile.length === 0)
    ) {
      const files = Array.isArray(item.uploadedFile)
        ? item.uploadedFile
        : [item.uploadedFile];
      files.forEach((file) => {
        tableUploadedFiles.push({
          fileType: "template_upload",
          templateId: item.id || item.fileId,
          templateName: item.name || item.fileName,
          filePath:
            typeof file === "string"
              ? file
              : file.url || file.filePath || file.name,
          fileName: item.name || item.fileName,
        });
      });
    }
  });

  // 合并所有文件
  const allFileObjects = [...fileObjects, ...tableUploadedFiles];

  // 整理明细项数据
  const items = form.items.map((item) => {
    if (item.itemType === "family_relation") {
      return {
        itemType: item.itemType,
        familyRelationTitle: item.familyRelationTitle,
        familyRelationName: item.familyRelationName,
        familyRelationAge: item.familyRelationAge,
        familyRelationPolitics: item.familyRelationPolitics,
        familyRelationWorkUnit: item.familyRelationWorkUnit,
      };
    } else {
      return {
        itemType: item.itemType,
        startTime: item.startTime,
        endTime: item.endTime,
        orgName: item.orgName,
        positionName: item.positionName,
        remark: item.remark,
      };
    }
  });

  const submitData = {
    ...form,
    fileObjects: allFileObjects,
    items,
  };
  delete submitData.validTime;
  if (Array.isArray(submitData.enrollFile)) {
    submitData.enrollFile = submitData.enrollFile[0]?.url || "";
  }

  if (form.id != undefined) {
    editItem(submitData)
      .then(() => {
        proxy.$modal.msgSuccess("修改成功");
        submitApproval({
          businessId: form.id,
          approvalTypeCode: "enroll_flow",
          approvalInfo: JSON.stringify(form),
        });
        router.back();
      })
      .catch((error) => {
        console.error("保存并提交失败:", error);
        saveSubmitLoading.value = false;
      }).finally(() => {
        saveSubmitLoading.value = false;
      });
  } else {
    addItem(submitData)
      .then((res) => {
        proxy.$modal.msgSuccess("新增成功");
        if (res.data) {
          form.id = res.data;
          submitApproval({
            businessId: res.data,
            approvalTypeCode: "enroll_flow",
            approvalInfo: JSON.stringify(form),
          });
        }
        router.back();
      })
      .catch((error) => {
        console.error("保存并提交失败:", error);
        saveSubmitLoading.value = false;
      }).finally(() => {
        saveSubmitLoading.value = false;
      });
  }
};

// 通过审批
const handleApprovePass = () => {
  if (approvePassLoading.value) return;

  approvePassLoading.value = true;
  const approvalData = {
    approvalInfoId: form.approvalInfoId,
    approvalNodeId: form.approvalNodeId,
    approvalStatus: "approved",
    remark: form.approvalRemark,
  };

  handleApproval(approvalData)
    .then(() => {
      proxy.$modal.msgSuccess("审批通过");
      router.back();
    })
    .catch((error) => {
      console.error("审批通过失败:", error);
    })
    .finally(() => {
      approvePassLoading.value = false;
    });
};

// 驳回审批
const handleApproveReject = () => {
  if (!form.approvalRemark) {
    proxy.$modal.msgError("请填写审核意见");
    return;
  }

  if (approveRejectLoading.value) return;

  approveRejectLoading.value = true;
  const approvalData = {
    approvalInfoId: form.approvalInfoId,
    approvalNodeId: form.approvalNodeId,
    approvalStatus: "rejected",
    remark: form.approvalRemark,
  };

  handleApproval(approvalData)
    .then(() => {
      proxy.$modal.msgSuccess("已驳回");
      router.back();
    })
    .catch((error) => {
      console.error("审批驳回失败:", error);
    })
    .finally(() => {
      approveRejectLoading.value = false;
    });
};

// 校验导出报名表的必填字段
const validateExportFields = () => {
  const errors = [];

  // 1. 报名年度
  if (!form.yearNum) {
    errors.push("请选择报名年度");
  }

  // 2. 个人信息
  if (!form.userName) {
    errors.push("请输入姓名");
  }
  if (form.sex === undefined || form.sex === null || form.sex === "") {
    errors.push("请选择性别");
  }
  if (!form.nation) {
    errors.push("请选择民族");
  }
  if (!form.idCard) {
    errors.push("请输入身份证号");
  }
  if (!form.origin) {
    errors.push("请输入籍贯");
  }
  if (!form.birthPlace) {
    errors.push("请输入出生地");
  }
  if (!form.political) {
    errors.push("请选择政治面貌");
  }
  // 当政治面貌选择"中共党员"时，入党时间必填
  if (form.political) {
    const partyMemberValue = political_status.value?.find(
      (item) => item.label === "中共党员"
    )?.value;
    if (form.political === partyMemberValue && !form.joinPartyDate) {
      errors.push("政治面貌为中共党员时，入党时间必填");
    }
  }
  if (!form.birthday) {
    errors.push("出生年月不能为空");
  }
  if (form.age === undefined || form.age === null || form.age === "") {
    errors.push("年龄不能为空");
  }
  if (!form.phonenumber) {
    errors.push("请输入手机号码");
  }
  if (!form.healthStatus) {
    errors.push("请选择健康状况");
  }

  // 2.1. 家庭主要成员及重要社会关系 - 至少需要1条
  const familyRelationItems = form.items.filter(
    (item) => item.itemType === "family_relation"
  );
  if (!familyRelationItems || familyRelationItems.length === 0) {
    errors.push("家庭主要成员及重要社会关系至少需要添加1条");
  }

  // 3. 教育信息（全日制）- 必填
  if (!form.fulltimeQualification) {
    errors.push("请选择最高学历（全日制）");
  }
  if (!form.fulltimeUniversity) {
    errors.push("请输入毕业高校（全日制）");
  }
  if (!form.fulltimeCollege) {
    errors.push("请输入毕业院系（全日制）");
  }
  if (!form.fulltimeJoinDate) {
    errors.push("请选择入学时间（全日制）");
  }
  if (!form.fulltimeGraduateDate) {
    errors.push("请选择毕业时间（全日制）");
  }
  if (!form.fulltimeMajor) {
    errors.push("请输入毕业专业（全日制）");
  }
  if (!form.fulltimeGrantUnit) {
    errors.push("请输入学位授予单位（全日制）");
  }
  if (!form.fulltimeAcademic) {
    errors.push("请输入学科专业名称（全日制）");
  }
  if (!form.fulltimeGrantDate) {
    errors.push("请选择学位授予年月（全日制）");
  }

  // 4. 教育信息（在职）- 非必填，跳过

  // 5. 外语
  if (!form.languageLevel) {
    errors.push("请选择外语等级");
  }
  if (!form.languageScore) {
    errors.push("请输入外语分数");
  }

  // 6. 工作信息
  if (!form.trainDeptId) {
    errors.push("请选择现任职单位");
  }
  if (!form.practiceDeptName) {
    errors.push("请输入现任职部门");
  }
  if (!form.position) {
    errors.push("请输入现任职务");
  }
  if (!form.firstWorkDate) {
    errors.push("请选择参加工作时间");
  }
  if (!form.firstJoinFawDate) {
    errors.push("请选择首次入职中国一汽时间");
  }
  if (!form.performanceN1) {
    errors.push(`请输入${performanceN1Label.value}`);
  }
  if (!form.performanceN2) {
    errors.push(`请输入${performanceN2Label.value}`);
  }
  if (!form.performanceN3) {
    errors.push(`请输入${performanceN3Label.value}`);
  }
  if (!form.professionTitle) {
    errors.push("请选择职称");
  }

  // 7. 工作业绩
  if (!form.achievementDesc) {
    errors.push("请输入从事工作及主要业绩");
  }

  // 8. 报名信息
  if (!form.trainMajor) {
    errors.push("请选择申报专业领域");
  }
  if (!form.trainUniversity) {
    errors.push("请选择申报高校");
  }
  if (!form.trainUnit1Id) {
    errors.push("请选择培养单位1");
  }

  // 9. 获奖、获得荣誉、发明专利、论文 - 非必填，跳过

  return errors;
};

// 校验信息提交的必填字段（包含协议列表校验）
const validateSubmitFields = () => {
  const errors = validateExportFields();

  // 10. 协议列表校验：每一项都必须上传文件
  if (enrollTimeFileList.value && enrollTimeFileList.value.length > 0) {
    enrollTimeFileList.value.forEach((item, index) => {
      if (
        !item.uploadedFile ||
        (Array.isArray(item.uploadedFile) && item.uploadedFile.length === 0)
      ) {
        const itemName = item.name || item.fileName || `第${index + 1}项`;
        errors.push(`请上传${itemName}的文件`);
      }
    });
  }

  return errors;
};

// 报名表导出
const handleExportDetail = async () => {
  // 校验必填字段
  const errors = validateExportFields();
  if (errors.length > 0) {
    ElMessage.warning(errors[0]);
    return;
  }

  exportDetailLoading.value = true;
  try {
    await submitForm();
    console.log(form.id, "xxxx");
    await downloadFileByApi(
      "biz/mdt/enroll/export/detail",
      { enrollId: form.id },
      `报名表_${form.userName || form.id}_${new Date().getTime()}.docx`
    );
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error(error.message || "操作失败，请稍后重试");
  } finally {
    exportDetailLoading.value = false;
  }
};

// 获取报名时间附件列表
const fetchEnrollTimeFileList = async () => {
  try {
    const res = await getValidEnrollTime();
    if (
      res.data &&
      res.data.fileObjects &&
      Array.isArray(res.data.fileObjects)
    ) {
      // 为每个附件添加 uploadedFile 字段用于上传
      enrollTimeFileList.value = res.data.fileObjects.map((file) => ({
        ...file,
        name: file.fileName || file.name || "",
        uploadedFile: [],
      }));
    } else {
      enrollTimeFileList.value = [];
    }
  } catch (error) {
    console.error("获取报名时间附件列表失败:", error);
    enrollTimeFileList.value = [];
  }
};

// 下载模板（参考 file-upload 组件的下载逻辑）
const handleDownloadTemplate = (row) => {
  if (!row.filePath && !row.url) {
    ElMessage.warning("模板文件不存在");
    return;
  }
  // 使用与 file-upload 组件相同的下载逻辑
  downloadFile({
    filePath: row.filePath,
    url: row.url,
    fileName: row.fileName,
    name: row.name,
  }).catch((error) => {
    console.error("下载模板失败:", error);
    ElMessage.error("下载模板失败，请稍后重试");
  });
};

// 取消/返回
const handleCancel = () => {
  router.back();
};

// 初始化
onMounted(async () => {
  await Promise.all([
    fetchYearOptions(),
    fetchDropdownOptions(),
    fetchRegisterList(),
    fetchEnrollTimeFileList(),
  ]);
  // 如果是学生角色且是新增模式，设置自己的姓名
  if (isStudentRole.value && !id) {
    form.userName = userStore.name || "";
  }
  await loadDetail();
});
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
  }
}

.avatar-delete-btn {
  width: 178px;
}
</style>
